#include "./qihai_tcpserver/TcpServer.hpp"
#include "./qihai_tcpserver/Unit.hpp"

#include <fstream>

using namespace qihai;

const char* WWWHEAD = "./wwwroot";
void func(TcpServer* server, ClientInfo* clientInfo)
{
    // 接收客户端传来的http请求
    bool isClose = false;
    std::string httpRequest = server->Recv(clientInfo->_clientSocket, isClose);
    // 对接收到的http请求报文进行处理，按照\r\n进行分行即可
    std::vector<std::string> requestSliced;
    StreamProcess::SlicedString(httpRequest, "\r\n", requestSliced);

    // 对请求行的地址进行分析
    std::vector<std::string> firstLine;
    StreamProcess::SlicedString(requestSliced[0], " ", firstLine);
    std::string path = WWWHEAD;
    if (firstLine[1] == "/") path += "/index.html";
    else path += firstLine[1];

    std::string httpResponse, text, line;
    // 用文件流读取网页
    std::ifstream in(path);
    if (in.is_open())
    {
        // 成功打开
        httpResponse += "HTTP/1.1 200 ok\r\n";
        while (std::getline(in, line))
            text += line;
        in.close();
    }
    else httpResponse += "HTTP/1.1 404 NotFound\r\n";  // 未知页面

    httpResponse += "\r\n";  // 空行
    httpResponse += text;  // 加上正文

    // 发送
    server->Send(clientInfo->_clientSocket, httpResponse);
    LOG(DEBUG) << httpResponse << std::endl;
}


int main(int argc, char* argv[])
{
    if (argc != 2 && argc != 3)
    {
        LOG(FATAL) << "./httpserver port or ./httpserver port -nodaemon" << std::endl;
        return 1;
    }
    bool isDaemon = true;
    if (argc == 3)
    {
        if (strcmp("-nodaemon", argv[2]) == 0)  // C中的比较字符串
            isDaemon = false;
        else
        {
            LOG(FATAL) << "./httpserver port or ./httpserver port -nodaemon" << std::endl;
            return 2;
        }
    }

    TcpServer* server = new TcpServer(atoi(argv[1]), isDaemon);
    server->Start(func);
    return 0;
}